package com.lingyu.biz;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lingyu.dao.CommentMapper;
import com.lingyu.dao.PrasieMapper;
import com.lingyu.dao.TopicMapper;
import com.lingyu.pojo.Comment;
import com.lingyu.pojo.Prasie;
import com.lingyu.pojo.Topic;
import com.lingyu.pojo.User;
@Service
public class TopicBiz implements ITopicBiz{
	@Autowired
	private TopicMapper topicMapper;
	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private PrasieMapper prasieMapper;

	@Override
	public List<Topic> getAllTopics() {
		List<Topic> topicList = topicMapper.getAllTopics();
		
		// 查询topic对应的comment
		for (Topic topic : topicList) {
			// list的第一个comment的fatherId肯定为null
			List<Comment> list =  commentMapper.getCommentsByTopicId(topic.getTopicId());
			List<Comment> duojiList = new ArrayList<Comment>();
			while(list.size()>0) { // 第一个的father永远是null
				Comment comment = list.get(0); // 永远拿第一个，而且father永远为null
				if(comment.getFather()==null){
					//1. 放入duojilist
					duojiList.add(comment);
					//2. 在list中删除掉
					list.remove(comment);
					//3. 找comment的儿子，并处理
					getChild(comment,list,duojiList);
				}else{
					throw new RuntimeException("数据是错的");
				}
			}
			topic.setComments(duojiList);
		}
		return topicList;
	}

	private void getChild(Comment father, List<Comment> list, List<Comment> duojiList) {
		
//		for (Comment comment : list) {
//			
//			if(comment.getFather()!=null && comment.getFather().getCommentId().equals(father.getCommentId())){
//				//1. 添加duojilist
//				duojiList.add(comment);
//				//2. 移除list
//				list.remove(comment);
//				//3. 找儿子
//				getChild(comment, list, duojiList);
//			}
//			
//		}
		
		for (int i = 0; i < list.size(); i++) {
			Comment comment = list.get(i);
			if(comment.getFather()!=null && comment.getFather().getCommentId().equals(father.getCommentId())){
				//1. 添加duojilist
				duojiList.add(comment);
				//2. 移除list
				list.remove(i);
				i--;
				//3. 找儿子
				getChild(comment, list, duojiList);
			}
					
		}
	}

	@Override
	public boolean addTopic(Topic topic) {
		int lines = topicMapper.insert(topic);
		return lines>0;
	}

	@Override
	public List<Prasie> getAllZan(User user) {
		return prasieMapper.getAllZan(user);
	}

	

}
